package com.study.springboot02study.controller;

import com.study.springboot02study.bean.User;
import com.study.springboot02study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    JdbcTemplate jdbcTemplate;


    //@Autowired
    //UserService userService;
    //
    //@ResponseBody
    //@GetMapping("/user")
    //public User getById(@RequestParam("id") int id){
    //    return userService.getById(id);
    //}

    @ResponseBody
    @GetMapping("/sql")
    public String queryFromDb(){
        Long along = jdbcTemplate.queryForObject("select count(*) from user", Long.class);
        return along.toString();
    }

    /**
     * 来登录页
     *
     * @return
     */
    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }


    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model) {
        if (StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())) {
            //把登陆的用户保存起来
            session.setAttribute("loginUser", user);
            //登陆成功重定向到main页面  防止表单重复提交
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "账号密码错误！");
            return "login";
        }
    }


    /**
     * 去main页面
     *
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {

        ////是否登陆  拦截器，过滤器
        //Object loginUser = session.getAttribute("loginUser");
        //if (loginUser != null) {
        //    return "main";
        //} else {
        //    //回到登录页
        //    model.addAttribute("msg", "请重新登录！");
        //    return "login";
        //}
        return "main";
    }
}
